package com.example.ploy4j.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import static org.springframework.security.config.Customizer.withDefaults;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(authorizeRequests ->
                authorizeRequests
                    .requestMatchers("/css/**", "/js/**", "/images/**", "/webjars/**", "/favicon.ico").permitAll() // Allow static resources
                    .requestMatchers("/login", "/error").permitAll() // Allow access to login and error pages
                    .requestMatchers("/api/**").authenticated() // Secure API endpoints
                    .anyRequest().authenticated() // All other requests need authentication
            )
            .formLogin(formLogin ->
                formLogin
                    .loginPage("/login") // Custom login page URL
                    .defaultSuccessUrl("/", true) // Redirect to home page on successful login
                    .permitAll()
            )
            .logout(logout ->
                logout
                    .logoutSuccessUrl("/login?logout")
                    .permitAll()
            )
            .csrf(AbstractHttpConfigurer::disable);
            // .csrf(withDefaults()); // Enable CSRF with defaults if using stateful sessions

        return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService(PasswordEncoder passwordEncoder) {
//        UserDetails user = User.builder()
//                .username("user")
//                .password(passwordEncoder.encode("password"))
//                .roles("USER")
//                .build();
        UserDetails admin = User.builder()
                .username("ploy")
                .password(passwordEncoder.encode("ploypass1"))
                .roles("ADMIN", "USER")
                .build();
        return new InMemoryUserDetailsManager( admin);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
} 